package com.demo.servlet.demo1221.demo01;

import com.demo.servlet.demo1221.demo01.entity.Person;
import com.demo.servlet.demo1221.demo01.entity.Student;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/demo1221/demo01.do")
public class Demo01Servlet extends BaseServlet {
    public void contextOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.拿到 ServletContext 对象
        ServletContext servletContext = this.getServletContext();
        //添加属性
        servletContext.setAttribute("context", "ContextValue11111");
        //替换属性
        servletContext.setAttribute("context", "ContextValue22222");
        //删除属性
        servletContext.removeAttribute("context");
    }

    public void sessionOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.拿到 Session 对象
        HttpSession session = request.getSession();
        //添加属性
        session.setAttribute("session", "sessionValue11111");
        //替换属性
        session.setAttribute("session", "sessionValue22222");
        //删除属性
        session.removeAttribute("session");
    }

    public void requestOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.拿到 Request 对象
        //添加属性
        request.setAttribute("request", "requestValue11111");
        //替换属性
        request.setAttribute("request", "requestValue22222");
        //删除属性
        request.removeAttribute("request");
    }

    public void addPerson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Person p = new Person("小明", 20, "男");
        request.getSession().setAttribute("person", p);
    }

    public void removePerson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().removeAttribute("person");
    }

    public void addStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Student p = new Student(1, "小明", 20);
        request.getSession().setAttribute("student", p);
    }

    public void removeStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().removeAttribute("student");
    }
}
